package cn.rongdao.jrkabao.util.login;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;

import com.netease.nis.captcha.Captcha;

import cn.rongdao.jrkabao.BuildConfig;


/**
 * Created by jiangyongxing on 2017/7/11.
 * 描述：
 */

public class YiDunUtil {

    public static class Builder {
        public Context mContext;
        Captcha mCaptcha;
        AsyncTask<Void, Void, Boolean> mLoginTask;
        CaptchaCallback mCaptchaCallback;

        public Builder(Context context) {
            this.mContext = context;
        }

        public YiDunUtil.Builder setLoginCaptchaListener(CaptchaCallback captchaCallback) {
            this.mCaptchaCallback = captchaCallback;
            return this;
        }

        public YiDunUtil.Builder create() {
            LoginCaptchaListener loginCaptchaListener = new LoginCaptchaListener() {
                @Override
                public void onValidate(String result, String validate, String message) {
                   if (mCaptchaCallback!=null){
                       if (validate.length() > 0) {
                           mCaptchaCallback.onSuccess(validate);
                       } else {
                           mCaptchaCallback.onFailed();
                       }
                   }
                }

                @Override
                public void onCancel() {
                    if (mLoginTask != null) {
                        if (mLoginTask.getStatus() == AsyncTask.Status.RUNNING) {
//                        Log.i(TAG, "stop mLoginTask");
                            mLoginTask.cancel(true);
                        }
                    }
                }
            };

            if (mCaptcha == null) {
                mCaptcha = new Captcha(mContext);
            }
            mCaptcha.setCaptchaId(BuildConfig.YIDUN_KEY);
            mCaptcha.setCaListener(loginCaptchaListener);

            //可选：开启debug
            mCaptcha.setDebug(false);
            //可选：设置超时时间
            mCaptcha.setTimeout(10000);



            return this;
        }

        @SuppressLint("StaticFieldLeak")
        public void show() {
            mLoginTask = new LoginAsyncTask(mCaptcha) {
                @Override
                protected void onCancelled() {
                    mLoginTask = null;
                }
            };
            //关闭mLoginTask任务可以放在myCaptchaListener的onCancel接口中处理
            mLoginTask.execute();
            //必填：初始化 captcha框架
            mCaptcha.start();
        }
    }

    public interface CaptchaCallback {
        void onSuccess(String validate);

        void onFailed();
    }
}
